import Mock from 'mockjs'

// 用户数据模型
export interface User {
  id: number
  name: string
  email: string
  phone: string
  avatar: string
  role: string
  createdAt: string
}

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟错误概率
const shouldError = (rate = 0.1) => Math.random() < rate

// 生成单个随机用户数据
const generateRandomUser = (): User => {
  return Mock.mock({
    'id|+1': 1,
    'name': '@cname',
    'email': '@email',
    'phone': '@integer(13000000000, 18999999999)',
    'avatar': '@image(200x200, @color, @character)',
    'role|1': ['admin', 'user', 'guest'],
    'createdAt': '@datetime'
  })
}

// 获取用户列表
const mockGetUsers = async (options: any) => {
  console.log('Mock.js 拦截了 /api/users GET 请求', options)
  
  // 模拟网络延迟
  await delay(Math.random() * 1000 + 500) // 500-1500ms的延迟
  
  // 模拟错误情况
  if (shouldError(0.1)) { // 10%的错误率
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    }
  }
  
  // 解析查询参数
  const url = new URL(options.url, 'http://localhost')
  const page = parseInt(url.searchParams.get('page') || '1')
  const pageSize = parseInt(url.searchParams.get('pageSize') || '10')
  
  // 生成用户数据
  const users: User[] = []
  const total = 47 // 假设总共有47个用户
  const totalPage = Math.ceil(total / pageSize)
  
  // 生成当前页的用户数据
  for (let i = 0; i < pageSize; i++) {
    const user = generateRandomUser()
    user.id = (page - 1) * pageSize + i + 1
    users.push(user)
  }
  
  return {
    code: 200,
    message: 'success',
    data: {
      list: users,
      pagination: {
        page,
        pageSize,
        total,
        totalPage
      }
    }
  }
}

// 获取单个用户详情
const mockGetUserById = async (options: any) => {
  console.log('Mock.js 拦截了 /api/users/:id GET 请求', options)
  
  // 模拟网络延迟
  await delay(Math.random() * 1000 + 300) // 300-1300ms的延迟
  
  // 模拟错误情况
  if (shouldError(0.05)) { // 5%的错误率
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    }
  }
  
  // 从URL中提取用户ID
  const urlParts = options.url.split('/')
  const userId = parseInt(urlParts[urlParts.length - 1])
  
  // 生成用户数据
  const user = generateRandomUser()
  user.id = userId
  
  return {
    code: 200,
    message: 'success',
    data: user
  }
}

// 创建用户
const mockCreateUser = async (options: any) => {
  console.log('Mock.js 拦截了 /api/users POST 请求', options)
  
  // 模拟网络延迟
  await delay(Math.random() * 1000 + 500) // 500-1500ms的延迟
  
  // 模拟错误情况
  if (shouldError(0.05)) { // 5%的错误率
    return {
      code: 500,
      message: '创建用户失败',
      data: null
    }
  }
  
  // 解析请求体
  let body = {}
  try {
    body = JSON.parse(options.body)
  } catch (e) {
    console.error('解析请求体失败:', e)
  }
  
  // 生成新用户
  const newUser = generateRandomUser()
  newUser.id = Mock.mock({'id|+1': 1000}).id
  Object.assign(newUser, body)
  
  return {
    code: 200,
    message: '用户创建成功',
    data: newUser
  }
}

// 更新用户
const mockUpdateUser = async (options: any) => {
  console.log('Mock.js 拦截了 /api/users/:id PUT 请求', options)
  
  // 模拟网络延迟
  await delay(Math.random() * 1000 + 500) // 500-1500ms的延迟
  
  // 模拟错误情况
  if (shouldError(0.05)) { // 5%的错误率
    return {
      code: 500,
      message: '更新用户失败',
      data: null
    }
  }
  
  // 解析请求体
  let body = {}
  try {
    body = JSON.parse(options.body)
  } catch (e) {
    console.error('解析请求体失败:', e)
  }
  
  // 从URL中提取用户ID
  const urlParts = options.url.split('/')
  const userId = parseInt(urlParts[urlParts.length - 1])
  
  // 生成更新后的用户数据
  const updatedUser = generateRandomUser()
  updatedUser.id = userId
  Object.assign(updatedUser, body)
  
  return {
    code: 200,
    message: '用户更新成功',
    data: updatedUser
  }
}

// 删除用户
const mockDeleteUser = async (options: any) => {
  console.log('Mock.js 拦截了 /api/users/:id DELETE 请求', options)
  
  // 模拟网络延迟
  await delay(Math.random() * 1000 + 300) // 300-1300ms的延迟
  
  // 模拟错误情况
  if (shouldError(0.05)) { // 5%的错误率
    return {
      code: 500,
      message: '删除用户失败',
      data: null
    }
  }
  
  // 从URL中提取用户ID
  const urlParts = options.url.split('/')
  const userId = parseInt(urlParts[urlParts.length - 1])
  
  return {
    code: 200,
    message: '用户删除成功',
    data: {
      id: userId
    }
  }
}

// 注册 Mock 路由
Mock.mock('/api/users', 'get', mockGetUsers)
Mock.mock('/api/users', 'post', mockCreateUser)
Mock.mock(/^\/api\/users\/\d+/, 'get', mockGetUserById)
Mock.mock(/^\/api\/users\/\d+/, 'put', mockUpdateUser)
Mock.mock(/^\/api\/users\/\d+/, 'delete', mockDeleteUser)

export default Mock